extends CharacterBody2D

@export var health:int
@export var damage:int
@export var speed: float
@export var animator:AnimatedSprite2D
@onready var damage_emitter:=$DamageEmitter
@export var jump_intensity : float
@onready var sprite = $AnimatedSprite2D
enum State {IDLE,RUN,ATTACK,THUMP,TACKOFF,JUMP,LOAD}

const GRAVITY := 600.00
var state = State.IDLE
var height = 0.00
var height_speed = 0.00
var animate = {
	State.IDLE : 'idle',
	State.RUN : 'run',
	State.ATTACK : 'attack',
	State.THUMP : 'thump',
	State.TACKOFF:'tackoff',
	State.JUMP:'jump',
	State.LOAD:'load'
}

func _ready() -> void:
	damage_emitter.area_entered.connect(on_emit_damage.bind())

func _process(_delta: float) -> void:
	handle_input()
	handle_movement()
	handle_animated()
	handle_air_time(_delta)
	sprite.position = Vector2.UP * height
	flip_sprite()
	move_and_slide()

func handle_movement():
	if can_move():
		if velocity.length() == 0:
			state = State.IDLE
		else:
			state = State.RUN

func handle_input():
	var direction := Input.get_vector("left","right","up","down")
	velocity = direction  * speed
	if can_attack() and Input.is_action_just_pressed("attack"):
		state = State.ATTACK
	if can_attack() and Input.is_action_pressed("thump"):
		state = State.THUMP
	if can_jump() and Input.is_action_pressed("jump"):
		state = State.TACKOFF
	
func handle_animated():
	animator.play(animate[state])

func handle_air_time(delta : float):
	if state == State.JUMP:
		height += height_speed * delta
		if height < 0:
			height = 0
			state = State.LOAD
		else:
			height_speed -= GRAVITY * delta

func can_attack():
	return state == State.IDLE or state == State.RUN	
func can_move():
	return state == State.IDLE or state == State.RUN
func can_jump():
	return state == State.IDLE or state == State.RUN	

func flip_sprite():
	if velocity.x > 0:
		animator.flip_h = false
		damage_emitter.scale.x = 1
	elif velocity.x < 0:
		animator.flip_h = true
		damage_emitter.scale.x = -1

func _on_animation_finished() -> void: 
	if state == State.TACKOFF:
		state = State.JUMP
		height_speed = jump_intensity
	elif not can_move():
		state = State.IDLE
		damage_emitter.monitoring = true
		await get_tree().create_timer(0.1).timeout  # 等待1帧
		damage_emitter.monitoring = false
		

func on_emit_damage(damage_receive:DamageReceiver):
	var direction := Vector2.LEFT if damage_receive.global_position.x < global_position.x else Vector2.RIGHT
	damage_receive.damage_receiver.emit(damage,direction)
